<?php

namespace App\Http\Middleware;

use Closure;
use Laravel\Passport\Token;
use Lcobucci\JWT\Parser;
use App\Models\User;
use Illuminate\Support\Facades\Auth;

class MergeCompanyId
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $access_token = $request->bearerToken();
        if ($access_token) {
            $token_id = (new Parser())->parse($access_token)->getClaim('jti');
            $token = Token::find($token_id);
            if ($token) {
                //如果grant_type为client_credentials，则从client中获取user_id,否则从token中获取user_id(grant_type为password)
                $user_id = $token->client->user_id ?? $token->user_id;
                $user = User::find($user_id);
                if ($user) {
                    $request->merge(['user_id' => $user_id, 'company_id' => $user->company_id]);
                }
            }
        }

        return $next($request);
    }
}
